package com.qf.iot.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.iot.Mapper.QfProductMapper;
import com.qf.iot.core.vo.R;
import com.qf.iot.dto.PageDto;
import com.qf.iot.entity.QfProduct;
import com.qf.iot.service.QfProductService;
import com.qf.iot.utils.SnowflakeIdGenerator;
import com.qf.iot.vo.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 作者：肖骏麟
 * 时间:2023/10/28 10:14
 * 描述：优化小子
 */
@Service
public class QfProductServiceImpl extends ServiceImpl<QfProductMapper, QfProduct> implements QfProductService {

    public PageResult<QfProduct> page(PageDto<QfProduct> pageDto) {
        //分页信息
        IPage<QfProduct> page = new Page<>(pageDto.getNow(),pageDto.getSize());

        //条件
        QueryWrapper<QfProduct> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(pageDto.getWhere().getName())){
            queryWrapper.lambda().like(QfProduct::getName,pageDto.getWhere().getName());
        }

        IPage<QfProduct> pageInfo = this.baseMapper.selectPage(page, queryWrapper);
        //封装分页结果
        PageResult<QfProduct> pageResult = new PageResult<>();
        pageResult.setPages(pageInfo.getPages());
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setList(pageInfo.getRecords());
        return pageResult;
    }
    @Transactional
    @Override
    public R insert(QfProduct qfProduct) {
        //查询是否存在相同的产品名字
        QueryWrapper<QfProduct> qfProductQueryWrapper = new QueryWrapper<>();
        qfProductQueryWrapper.eq("name", qfProduct.getName());
        QfProduct qfProduct1 = baseMapper.selectOne(qfProductQueryWrapper);
        if (!StringUtils.isEmpty(qfProduct1)){
            return R.fail("已存在该产品");
        }else {
            // 如果产品名字不重复，则执行插入操作

            long id = IdWorker.getId();

            qfProduct.setCreateTime(new Date());
            qfProduct.setUpdateTime(new Date());
            baseMapper.insert(qfProduct);
            return R.ok("产品添加成功");
        }
    }
}
